<!doctype html>
<canvas id="canvas" style="border: 1px solid red;" onmousedown="Mouse.mousedown()" onmouseup="Mouse.mouseup()"></canvas>

<script>
    /*jshint browser:true*/

    var BLANK_IMG =
        '';

    var canvas = document.getElementById('canvas')
        , g = canvas.getContext('2d');

    var ws = new WebSocket('ws://localhost:9002', 'minicap');
    ws.binaryType = 'blob';

    ws.onclose = function () {
        console.log('onclose', arguments)
    };

    ws.onerror = function () {
        console.log('onerror', arguments)
    };

    ws.onmessage = function (message) {
        var blob = new Blob([message.data], {type: 'image/jpeg'});
        var URL = window.URL || window.webkitURL;
        var img = new Image();
        img.onload = function () {
            console.log(img.width, img.height);
            canvas.width = img.width / 3;
            canvas.height = img.height / 3;
            g.drawImage(img, 0, 0, img.width / 3, img.height / 3);
            img.onload = null;
            img.src = BLANK_IMG;
            img = null;
            u = null;
            blob = null;
        };
        var u = URL.createObjectURL(blob);
        img.src = u
    };

    ws.onopen = function () {
        console.log('onopen', arguments);
        ws.send('1920x1080/0')
    };

    //minitouch
    var wsTouch = new WebSocket('ws://localhost:9002');
    var Mouse = {
        x: 0,
        y: 0,
        mousedown: function (event) {
            var e = event || window.event;
            var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
            var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
            Mouse.x = (e.pageX || e.clientX + scrollX) * 3 - 25;
            Mouse.y = (e.pageY || e.clientY + scrollY) * 3 - 30;
        },
        mouseup: function (event) {
            var e = event || window.event;
            var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
            var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
            upx = (e.pageX || e.clientX + scrollX) * 3 - 25;
            upy = (e.pageY || e.clientY + scrollY) * 3 - 30;
            lenx = Math.abs(Mouse.x - upx);
            leny = Math.abs(Mouse.y - upy);
            if (lenx > 30 || leny > 30) {
                //swipe
                alert('swipe');
            } else {
                //click
                wsTouch.send('d 0 ' + upx + ' ' + upy + ' 50\\n');
                wsTouch.send('c\\n');
                wsTouch.send('u\\n');
                wsTouch.send('c\\n');
            }
        }
    };

</script>
